package net.app.help.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import net.app.help.R;
import net.app.help.dialogs.EditMessageDialog;
import net.app.help.adapters.MessagesListViewAdapter;
import net.app.help.db.DatabaseAdapter;
import net.app.help.model.Message;

import java.util.ArrayList;

public class MessagesActivity extends ActionBarActivity implements EditMessageDialog.OnConfirmInterface {

	private boolean[] selected;
	private ArrayList<Message> messages;
	private DatabaseAdapter da;

	private Button addMes, remMes;
	private ListView mesList;
	private MessagesListViewAdapter mesListAdapter;

	private EditText title, content;

	/**Add message button on click listener. Opens AddMessageDialog.*/
	private View.OnClickListener addMesOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("addMesOnClickListener", "onClick: CLICKED");
//			AddMessageDialog addMessageDialog = new AddMessageDialog();
//			addMessageDialog.show(getSupportFragmentManager(), "Add New Message TAG");
			//create dialog to create new group
			AlertDialog.Builder builder = new AlertDialog.Builder(MessagesActivity.this);
			builder.setTitle("Add new message");
			View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_message, null);
			title = (EditText) dialogView.findViewById(R.id.dialog_add_msg_et_title);
			content = (EditText) dialogView.findViewById(R.id.dialog_add_msg_et_content);
			builder.setView(dialogView);
			builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (String.valueOf(title.getText()).equals("") || String.valueOf(content.getText()).equals("")) {
						showAlertDialog("Error", "Fill in the required fields");
					} else {
						Message m = new Message();
						m.setTitle(String.valueOf(title.getText()));
						m.setContent(String.valueOf(content.getText()));
						Log.d("Adding message to DB", "Message=" + m.toString());
						da.openToWrite();
						da.addMessage(m);
						da.close();
						updateAdapter();
						Toast.makeText(MessagesActivity.this, "Message successfully added", Toast.LENGTH_SHORT).show();
					}
				}
			});
			builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//...
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
	};
	/**Remove message button on click listener. Checks which messages in ListView are checked and
	 * removes them from DB with "deleteMessage(Message m)" method*/
	private View.OnClickListener remMesOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d("remMesOnClickListener", "onClick: CLICKED");
			selected = mesListAdapter.obtainSelected();

			if (checkIfAtLeastOneSelected()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(MessagesActivity.this);
				builder.setTitle("Confirm message deletion");
				builder.setMessage("Do you really want to delete checked messages?");
				builder.setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						da.openToWrite();
						for (int i = 0; i < selected.length; i++) {
							if (selected[i]) {
								Log.d("Deleting message", "Message=" + messages.get(i).toString());
								da.deleteMessage(messages.get(i));
							}
						}
						da.close();
						updateAdapter();
						Toast.makeText(MessagesActivity.this, "Messages successfully deleted", Toast.LENGTH_SHORT).show();
					}
				});
				builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//nič
					}
				});
				builder.create();
				builder.show();
			} else {
				showAlertDialog("Error", "Check message you want to delete");
			}
		}
	};

	private void setupViews() {
		da = new DatabaseAdapter(this);
		addMes = (Button) findViewById(R.id.act_mes_b_add_message);
		addMes.setOnClickListener(addMesOnClickListener);
		remMes = (Button) findViewById(R.id.act_mes_b_remove_message);
		remMes.setOnClickListener(remMesOnClickListener);
		mesList = (ListView) findViewById(R.id.act_mes_lv_message_list);
		mesList.setAdapter(mesListAdapter);
	}

	private void updateAdapter() {
		obtainData();
		mesListAdapter = new MessagesListViewAdapter(this, messages, da);
		mesList.setAdapter(mesListAdapter);
	}

	private void obtainData() {
		da.openToRead();
		messages = da.getAllMessages();
		da.close();
	}

	private boolean checkIfAtLeastOneSelected() {
		int counter = 0;
		for (int i=0; i<selected.length; i++) {
			if (selected[i])
				counter++;
		}
		if (counter != 0)
			return true;
		else
			return false;
	}

	private void showAlertDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MessagesActivity.this);
		builder.setTitle(title);
		builder.setMessage(message);
//				builder.setIcon(R.drawable.) //ALERT ICON TO BE SET
		builder.setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//NIČ
			}
		});
		builder.create();
		builder.show();
	}

	public void setSupportActionBarLogo() {
		getSupportActionBar().setDisplayShowHomeEnabled(true);
//		getSupportActionBar().setDisplayUseLogoEnabled(true);
//		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(R.drawable.help_app_icon);
//		getSupportActionBar().setLogo(R.drawable.help_app_icon);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_messages);
		setSupportActionBarLogo();
		setupViews();
		updateAdapter();

	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_messages, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
			case R.id.action_contacts:
				Intent c = new Intent(this, ContactsActivity.class);
				startActivity(c);
				return true;
			case R.id.action_groups:
				Intent g = new Intent(this, GroupsActivity.class);
				startActivity(g);
				return true;
			case R.id.action_messages:
				Intent m = new Intent(this, MessagesActivity.class);
				startActivity(m);
				return true;
			case R.id.action_settings:
				Intent i = new Intent(this, SettingsActivity.class);
				startActivity(i);
				return true;
			case R.id.action_instructions:
				Intent ins = new Intent(this, InstructionsActivity.class);
				startActivity(ins);
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}


	@Override
	public void onConfirmEditMessage() {
		Toast.makeText(this, "Message edited", Toast.LENGTH_SHORT).show();
		updateAdapter();
	}

	@Override
	public void onCancelEditMessage() {
		Toast.makeText(this, "Message edit cancelled", Toast.LENGTH_SHORT).show();
	}
}
